<template>
  <div class="rich-editor-page">
    <div class="header-box">
      <p>内容发布</p>
    </div>
    <div class="content-box">
      <el-form
        ref="richEditorRef"
        :model="formData"
        :rules="formRules"
        label-width="100px"
        class="rich-editor-form"
      >
        <el-form-item label="标题" prop="noticeTitle">
          <el-input v-model="formData.noticeTitle" maxlength="54" show-word-limit autocomplete="off" style="width: 400px" />
        </el-form-item>
        <el-form-item label="类型" prop="typeId">
          <el-select v-model="formData.typeId" style="width: 200px">
            <el-option v-for="item in contentTypeList" :key="item.id" :label="item.typeName" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item v-if="showDesc" label="描述" prop="noticePreview">
          <el-input v-model="formData.noticePreview" maxlength="80" show-word-limit type="textarea" :rows="4" autocomplete="off" style="width: 400px" />
        </el-form-item>
        <el-form-item label="来源" prop="source">
          <el-input v-model="formData.source" maxlength="40" show-word-limit autocomplete="off" style="width: 400px" />
        </el-form-item>
        <el-form-item v-if="!isLaw" label="缩略图" prop="imageId">
          <el-upload
            accept=".jpg, .jpeg, .png, .JPG, .JPEG, .PBG"
            action=""
            class="avatar-uploader"
            :show-file-list="false"
            :before-upload="beforeAvatarUpload"
            :http-request="uploadImg"
          >
            <img v-if="imgURl" :src="imgURl" class="avatar" alt="">
            <i v-else class="el-icon-plus avatar-uploader-icon" />
          </el-upload>
        </el-form-item>
        <el-form-item label="内容" prop="noticeText" style="width: 90%;">
          <RichEditor :value="noticeContent" :show-message="editorShowMessage" @input="changeRich" @editorBlur="editorBlur" />
        </el-form-item>
        <el-form-item label="附件" prop="attachName">
          <el-upload
            accept=".zip, .rar, .pdf, .doc, .docx, .xls, .xlsx , .ppt, .pptx , .png , .jpg , .jpeg"
            :multiple="false"
            action=""
            :limit="1"
            class="upload-demo"
            :before-upload="beforeAttachmentUpload"
            :on-exceed="handleExceed"
            :http-request="uploadAttachment"
            :file-list="fileList"
            :before-remove="beforeRemove"
          >
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">只能上传一个zip/rar/pdf/doc/docx/xls/xlsx/ppt/pptx/png/jpg/jpeg文件，且不超过10MB</div>
          </el-upload>
        </el-form-item>
        <el-form-item>
          <el-button v-permission="'contentRelease:submit'" type="primary" style="width: 100px" @click="onSubmit()">保存</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>
<script>
import RichEditor from '@/components/RichEditor/RichEditor';
import { GetContentTypeList, PublishContent, uploadImg, uploadThumb } from '@/api/submit';
import { compressImage } from '@/utils/compregressImg';
import store from '@/store';
export default {
  name: 'ContentRelease',
  components: {
    RichEditor
  },
  data() {
    return {
      fileList: [
        // {
        //   name: null,
        //   url: null
        // }
      ],
      formData: {},
      formRules: {
        noticeTitle: [
          {
            required: true, message: '标题不能为空', trigger: 'blur'
          }
        ],
        noticePreview: [
          {
            required: true, message: '描述不能为空', trigger: 'blur'
          }
        ],
        label: [
          {
            required: true, message: '请选择标签'
          }
        ],
        typeId: [
          {
            required: true, message: '请选择内容类型'
          }
        ],
        // imageId: [
        //   {
        //     required: true, message: '请上传缩略图'
        //   }
        // ],
        noticeText: [
          {
            required: true, validator: this.validateNoticeText, trigger: 'blur'
          }
        ]
      },
      contentTypeList: [],
      noticeContent: '',
      imgURl: '',
      editorShowMessage: false,
      isLaw: false,
      showDesc: true,
      attachment: {
        name: null,
        url: null
      }
    }
  },
  beforeDestroy() {
    store.commit('content/setContentInfo', null);
  },
  mounted() {
    this.getContentType();
    if (store && store.state.content.content_info) {
      const contentData = JSON.parse(JSON.stringify(store.state.content.content_info));
      this.formData = contentData;
      if (contentData.noticeText) {
        this.noticeContent = contentData.noticeText;
      }
      if (contentData.url) {
        // this.imgURl = process.env.VUE_APP_BASE_API + '/api/' + contentData.url;
        this.imgURl = window.location.origin + '/api/' + contentData.url;
      }
      if (contentData.attachmentUrl) {
        this.attachment.url = window.location.origin + '/api/' + contentData.attachmentUrl;
      }
      if (contentData.attachmentName) {
        this.attachment.name = contentData.attachmentName;
      }
      if (this.attachment.url && this.attachment.name) {
        this.fileList.push(this.attachment)
      }
    }
  },
  methods: {
    beforeRemove(file, fileList) {
      return this.$confirm(`确定移除 ${file.name}？`);
    },
    editorBlur() {
      this.$refs['richEditorRef'].validateField('noticeText');
    },
    validateNoticeText(rule, value, cb) {
      if (this.noticeContent && this.noticeContent.trim() !== '') {
        cb();
      } else {
        cb('内容不能为空')
      }
    },
    onSubmit() {
      // console.log('this.formData', this.formData)
      this.$refs['richEditorRef'].validate(res => {
        if (res) {
          const requestBody = {
            ...this.formData,
            status: 0
          }
          if (this.formData.id) {
            requestBody.id = this.formData.id;
          }
          if (this.formData.remark && this.formData.remark !== '') {
            this.formData.remark = '';
          }
          const arr = ['现任领导', '主要职能', '机构设置']
          if (arr.indexOf(this.getContentTypeName(this.formData.typeId)) !== -1) {
            const contentTypeName = this.getContentTypeName(this.formData.typeId)
            if (contentTypeName === '现任领导') {
              PublishContent(requestBody).then(res => {
                if (res.code === 200) {
                  this.$message.success('内容已保存至草稿');
                  this.imgURl = '';
                  this.formData = {};
                  this.noticeContent = '';
                  this.$refs['richEditorRef'].resetFields();
                  const obj = {
                    id: res.data,
                    type: 'preview'
                  }
                  this.$router.push({ path: '/depIntroduce', query: obj });
                }
              })
            } else if (contentTypeName === '主要职能') {
              PublishContent(requestBody).then(res => {
                if (res.code === 200) {
                  this.$message.success('内容已保存至草稿');
                  this.imgURl = '';
                  this.formData = {};
                  this.noticeContent = '';
                  this.$refs['richEditorRef'].resetFields();
                  const obj = {
                    id: res.data,
                    type: 'preview'
                  }
                  this.$router.push({ path: '/mainFunction', query: obj });
                }
              })
            } else if (contentTypeName === '机构设置') {
              // console.log(this.getContentTypeName(this.formData.typeId))
              PublishContent(requestBody).then(res => {
                if (res.code === 200) {
                  this.$message.success('内容已保存至草稿');
                  this.imgURl = '';
                  this.formData = {};
                  this.noticeContent = '';
                  this.$refs['richEditorRef'].resetFields();
                  const obj = {
                    id: res.data,
                    type: 'preview'
                  }
                  this.$router.push({ path: '/mechanismSetup', query: obj });
                }
              })
            } else {
              console.log('contentTypeName不在数组中', contentTypeName)
            }
          } else {
            // console.log(this.getContentTypeName(this.formData.typeId))
            PublishContent(requestBody).then(res => {
              if (res.code === 200) {
                this.$message.success('内容已保存至草稿');
                this.imgURl = '';
                this.formData = {};
                this.noticeContent = '';
                this.$refs['richEditorRef'].resetFields();
                const obj = {
                  id: res.data,
                  type: 'preview'
                }
                this.$router.push({ path: '/article', query: obj });
              }
            })
          }
        }
      })
    },
    changeRich(value) {
      // console.log(11111, value);
      this.noticeContent = value;
      this.formData.noticeText = value;
    },
    getContentType() {
      const formData = new FormData()
      // 第一个值是key,第二个是value
      formData.append('current', 1)
      formData.append('size', 999)
      const params = new URLSearchParams(formData)
      GetContentTypeList(params).then(res => {
        if (res.code === 200) {
          this.contentTypeList = res.data.records;
        }
      });
    },
    getContentTypeName(id) {
      for (let i = 0; i < this.contentTypeList.length; i++) {
        if (this.contentTypeList[i].id === id) {
          return this.contentTypeList[i].typeName
        } else {
          continue;
        }
      }
    },
    beforeAttachmentUpload(file) {
      const is1M = file.size / 1024 / 1024 < 10;

      const index = file.name.lastIndexOf('.');
      const Type = file.name.substr(index + 1, file.name.length);
      if (['pdf', 'doc', 'docx', 'xlsx', 'xls', 'ppt', 'pptx', 'zip', 'rar', 'png', 'jpg', 'jpeg'].indexOf(Type.toLowerCase()) === -1) {
        this.$message({
          type: 'warning',
          message: '请上传后缀名为pdf、doc、docx 、xlsx 、xls、 ppt 、 pptx 、zip 、rar 、png 、jpg 、jpeg的附件！'
        });
        return false;
      }
      // 限制文件上传大小
      if (!is1M) {
        this.$message.error('你上传的' + file.name + '文件过大，请上传小于10MB的文件。');
        return false
      }
      if (file.name.indexOf('@') !== -1 || file.name.indexOf('#') !== -1 || file.name.indexOf('""') !== -1 || file.name.indexOf('<') !== -1 || file.name.indexOf('>') !== -1 || file.name.indexOf('?') !== -1 || file.name.indexOf('|') !== -1 || file.name.indexOf('/') !== -1 || file.name.indexOf(':') !== -1 || file.name.indexOf('`\`') !== -1) {
        this.$message.warning('你上传的' + file.name + '文件有特殊字符，文件名中不可存在特殊字符,请重新上传');
        return false;
      }
      // this.formData.attachmentId = URL.createObjectURL(file);
      return true
    },
    handleExceed(files, fileList) {
      this.$message.warning(`文件上传数量已达上限`);
    },
    uploadAttachment(file) {
      const formData = new FormData();
      formData.append('file', file.file);
      uploadImg(formData).then(res => {
        if (res.code === 200) {
          this.$message.success('附件上传成功');
          this.formData.attachmentName = res.data.fileName;
          this.formData.attachmentUrl = res.data.url;
          this.formData.attachmentId = res.data.materialId;
        }
      });
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpg';
      const isPng = file.type === 'image/png';
      const isJpeg = file.type === 'image/jpeg';
      // 1MB=1024*1024(1MB=1024KB 1KB=1024B)
      const is1M = file.size / 1024 / 1024 < 10;
      // 限制文件上传类型
      if (!isJPG && !isPng && !isJpeg) {
        this.$message.error('上传图片只能是 png,jpg,jpeg 格式!');
        return false
      }

      // 限制文件上传大小
      if (!is1M) {
        this.$message.error('上传图片大小不能超过 10MB!');
        return false
      }
      this.formData.imageId = URL.createObjectURL(file);
      return true
    },
    uploadImg(file) {
      const formData = new FormData();
      formData.append('file', file.file);
      uploadImg(formData).then(res => {
        if (res.code === 200) {
          compressImage(file.file).then(data => {
            console.log(111111, data);
            const formData1 = new FormData();
            formData1.append('file', data.compressFile);
            formData1.append('materialId', res.data.materialId)
            uploadThumb(formData1).then(result => {
              if (result.code === 200) {
                this.$message.success('图片上传成功');
                // this.imgURl = process.env.VUE_APP_BASE_API + '/api/' + res.data.url;
                this.imgURl = window.location.origin + '/api/' + res.data.url;
                this.formData.imageId = res.data.materialId;
                this.$nextTick(() => {
                  this.$refs['richEditorRef'].clearValidate('imageId');
                });
              }
            })
          });
        }
      });
    }
  }
}
</script>
<style lang="scss" scoped>
.rich-editor-page {
  width: 100%;
  height: 100%;

  .header-box {
    width: 100%;
    height: 80px;
    line-height: 80px;
    background-color: #fff;

    p {
      margin-left: 30px;
      font-size: 28px;
      font-weight: 500;
      font-family: PingFangSC-Medium, PingFang SC;
    }
  }

  .content-box {
    overflow-y: auto;
    background-color: #fff;
    margin-top: 10px;
    width: 100%;
    height: calc(100% - 90px);
    padding: 30px;
    box-sizing: border-box;

    ::v-deep .avatar-uploader .el-upload {
      border: 1px dashed #d9d9d9;
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
    }

    ::v-deep .avatar-uploader .el-upload:hover {
      border-color: #409EFF;
    }

    ::v-deep .avatar-uploader-icon {
      font-size: 28px;
      color: #8c939d;
      width: 178px;
      height: 178px;
      line-height: 178px;
      text-align: center;
    }

    ::v-deep .avatar {
      width: 178px;
      height: 178px;
      display: block;
    }
  }
}
</style>

<style scoped>
.rich-editor-form::v-deep .el-textarea__inner {
  resize: none;
}
.el-upload__tip{
  color: red;
  margin-top: 5px;
  font-size: 14px;
}
</style>
